package com.palm.core.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import org.sagacity.sqltoy.plugins.TypeHandler;

import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

public class JsonTypeHandler extends TypeHandler {
    @Override
    public boolean setValue(PreparedStatement pst, int paramIndex, int jdbcType, Object value) throws SQLException {
        return false;
    }

    @Override
    public Object toJavaType(String javaTypeName, Class genericType, Object jdbcValue) throws Exception {

        if (jdbcValue == null) {
            return null;
        }
        if (jdbcValue instanceof String) {

        } else {
            return null;
        }
        Class t = Class.forName(javaTypeName);
        if (genericType == null) {
            return JSON.parseObject((String) jdbcValue, t);
        } else {
            if (Map.class.isAssignableFrom(t)) {
                ParameterizedTypeImpl pt = new ParameterizedTypeImpl(new Type[]{String.class, genericType}, t, t);
                return JSON.parseObject((String) jdbcValue, pt);
            } else {
                ParameterizedTypeImpl pt = new ParameterizedTypeImpl(new Type[]{genericType}, t, t);
                return JSON.parseObject((String) jdbcValue, pt);
            }
        }
    }
}
